package com.siqi.hr.system.organization.dao.mysql;

import com.siqi.hr.common.Constants;
import com.siqi.hr.system.organization.dao.intf.MenuDao;
import com.siqi.hr.system.common.model.ModuleType;
import com.siqi.hr.system.organization.entity.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 权限菜单维护dao实现类层
 * @author     xiaogq
 * Created by xiaogoingqin on 2016/7/23.
 */
@Repository("menuDao")
public class MenuDaoImpl implements MenuDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Map<String, Object>> getInitMenuList(String roleid, ModuleType module) {
        Assert.hasText(roleid);
        Assert.notNull(module);
        StringBuilder sql = new StringBuilder().append(" select m.id,m.kind,m.level,m.name,m.pid,m.is_parent,m.url,m.icon from sys_org_menu m ");
        //如果不是管理员角色
        if (!roleid.equals(Constants.ROOTROLEID)) {
            sql.append(" join sys_org_role_menu rm on m.id = rm.menu_id ");
        }
        sql.append(" where m.flag = true ");
        sql.append(" and m.belong_mudule like '" + module.getModuleMark() + "' ");
        //如果不是管理员角色
        if (!roleid.equals(Constants.ROOTROLEID)) {
            sql.append(" and rm.role_id = '").append(roleid).append("' and rm.flag = true ");
        }
        sql.append(" order by level, position");
        try {
            return jdbcTemplate.query(sql.toString(), new RowMapper() {
                public Object mapRow(ResultSet rs, int arg1) throws SQLException {
                    Map<String,Object> map = new HashMap<String,Object>();
                    map.put("id", rs.getInt("id"));
                    map.put("kind",rs.getInt("kind"));
                    map.put("level", rs.getInt("level"));
                    map.put("text", rs.getString("name"));
                    map.put("pid", rs.getInt("pid"));
                    map.put("isParent",rs.getBoolean("is_parent"));
                    map.put("url", rs.getString("url"));
                    map.put("iconCls", rs.getString("icon") == null ? "" : rs.getString("icon"));
                    return map;
                }
            });
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Integer getMenuLevelOneMaxPosition() {
        String sql = "select max(position) from sys_org_menu where level = 1 and pid is null";
        return jdbcTemplate.queryForObject(sql,Integer.class);
    }

    @Override
    public int addMenu(Menu menu) {
        final StringBuffer sql = new StringBuffer("insert into sys_org_menu (name, level,is_parent,pid,position,url,flag,icon,entity_id,belong_mudule) ");
        sql.append(" values( '"+ menu.getName() +"',"+menu.getLevel()+","+menu.getIsparent()+","+menu.getPid()+","+menu.getPosition()+",");
        sql.append((menu.getUrl() == null ? null : new StringBuilder("'") .append(menu.getUrl()).append("'").toString())+","+menu.getFlag()+",");
        sql.append((menu.getIcon() == null ? null : new StringBuilder("'").append(menu.getIcon()).append("'").toString())+","+menu.getEntity().getTableCode()+",'"+menu.getBelongMudule()+"')");
        KeyHolder keyHolder = new GeneratedKeyHolder();
        this.jdbcTemplate.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection conn) {
                PreparedStatement ps = null;
                try {
                    ps = conn.prepareStatement(sql.toString(), new String[] { "id" });
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return ps;
            }
        }, keyHolder);

        return keyHolder.getKey().intValue();
    }

    @Override
    public void updateEntityMenuName(Integer entityId, String localization) {
        String sql = "select id,name,url from sys_org_menu where entity_id = " + entityId + " order by position";
        List<Map<String,Object>> list = this.jdbcTemplate.queryForList(sql);
        if (list != null && list.size() > 0)
            try {
                String oldEntityName = list.get(0).get("name").toString().trim();
                String[] updatesql = new String[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    Map<String,Object> map = list.get(i);
                    String oldname = map.get("name").toString();
                    String newname = oldname.indexOf(oldEntityName) >= 0 ? oldname.replaceAll(oldEntityName, localization) : oldname;
                    StringBuilder sb = new StringBuilder();
                    sb.append("update sys_org_menu set name = '").append(newname).append("' ");
                    if (map.get("url") != null && !map.get("url").toString().trim().equals("")) {
                        String oldurl = map.get("url").toString();
                        String newrul = oldurl.indexOf(oldEntityName) >= 0 ? oldurl.replaceAll(oldEntityName, localization) : oldurl;
                        sb.append(", url = '").append(newrul).append("' ");
                    }
                    sb.append(" where id = ").append(map.get("id"));
                    updatesql[i] = sb.toString();
                }
                this.jdbcTemplate.batchUpdate(updatesql);
            } catch (DataAccessException e) {
                e.printStackTrace();
            }
    }

}
